package medicalDocumentation.medicalRepository;

import entity.Medication;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class MedicationRepositorySessionBean implements MedicationRepositorySessionBeanRemote {

    public final String MEDICATION_CODE_REQUIRED = "Medication code required";
    public final String DUPLICATE_MEDICATION_CODE = "Duplicate medication code";
    @PersistenceContext
    private EntityManager entityManager;
    
    @Override
    public String addMedication(String code, String name, String remark) {
        if (code == null) {
            return MEDICATION_CODE_REQUIRED;
        }
        if (getMedicationByCode(code).size() > 0) {
            return DUPLICATE_MEDICATION_CODE;
        }
        Medication medication = new Medication();
        medication.setCode(code);
        medication.setName(name);
        medication.setRemark(remark);
        entityManager.persist(medication);
        entityManager.flush();
        return medication.getCode();
    }

    @Override
    public List<Medication> getMedicationByCode(String code) {
        String strQuery = "SELECT d FROM Medication d WHERE d.code = :inCode";
        Query query = entityManager.createQuery(strQuery);
        query.setParameter("inCode", code);
        return query.getResultList();
    }

    @Override
    public List<Medication> getAllMedication() {
        String strQuery = "SELECT m FROM Medication m";
        Query query = entityManager.createQuery(strQuery);
        return query.getResultList();
    }

    @Override
    public void deleteMedication(String code) {
        List medications = getMedicationByCode(code);
        if (medications.get(0) != null) {
            entityManager.remove(medications.get(0));
            entityManager.flush();
        }
    }

    @Override
    public void updateMedication(String code, String name, String remark) {
        Medication medication = getMedicationByCode(code).get(0);
        if (medication != null) {
            medication.setName(name);
            medication.setRemark(remark);
            entityManager.merge(medication);
            entityManager.flush();
        }
    }
}
